package com.cloud.phone.web_activity;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Handler;
import android.util.Log;
import android.view.accessibility.AccessibilityNodeInfo;
import android.webkit.WebView;

import com.blankj.utilcode.util.ScreenUtils;
import com.cloud.phone.R;
import com.cloud.phone.constants.Constants;
import com.cloud.phone.task.BaseTask;
import com.cloud.phone.task.TaskManager;
import com.cloud.phone.task.tiktok.TikTokTask;
import com.cloud.phone.tools.AccessibilityTool;
import com.cloud.phone.tools.LogUtils;
import com.cloud.phone.tools.MyUtils;
import com.cloud.phone.view.MyWebView;

import java.util.List;


public class NormalWebActivity extends BaseWebViewActivity {
    public MyWebView x5WebView;


    @Override
    protected int getContentRes() {
        return R.layout.activity_webview;
    }

    @Override
    public MyWebView getBase_webView() {
        x5WebView =findViewById(R.id.webView);
        return x5WebView;
    }

    @Override
    public void initFirst() {
        String url=getIntent().getStringExtra("url");
        setWebviewListener();
        if(!MyUtils.isEmpty(url)){
            x5WebView.loadUrl(url);
        }
    }


    public boolean isReceivedTitle;
    private void setWebviewListener() {
        x5WebView.initDefaultSetting(this);
        x5WebView.setOnWebPageChangeListener(new MyWebView.OnWebPageChangeListener() {
            @Override
            public void onReceivedTitle(WebView webView, String s) {
                if(isReceivedTitle){
                    return;
                }
                isReceivedTitle=true;
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        tryTime=0;
                        findTopBarAndClick();
                    }
                },2000);
            }

            @Override
            public void onPageStart(WebView webView, String s) {

            }

            @Override
            public void onPageFinished(WebView webView, String s) {

            }
        });
        x5WebView.setOverridAndInterCeptListener(new MyWebView.OnShouldOverridUrlListener() {
            @Override
            public void onIntentOpenOtherApp(WebView webView, String url) {
                startThirdpartyApp(url);
            }
        });
    }


    @Override
    public void onResume() {
        super.onResume();
        BaseTask task=TaskManager.getInstance().getCurrentTask();
        if(task!=null&&task.taskStatus==TikTokTask.FINISH){
            finish();
        }
    }

    /**
     * 打开第三方app。如果没安装则跳转到应用市场
     * @param url
     */
    public void startThirdpartyApp(String url)
    {
        try {
            Intent intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME); // 注释1
            startActivity(intent);
        }
        catch (Exception e)
        {
            Log.e("WebView", e.getMessage());
        }
    }

    public boolean isFindDoing;
    int tryTime=0;
    private synchronized void findTopBarAndClick() {
        if(MyUtils.isEmpty(TaskManager.getInstance().tasks)){
           return;
        }
        if(isFindDoing){
            return;
        }
        BaseTask task=TaskManager.getInstance().getCurrentTask();
        String currentPkg = AccessibilityTool.getInstance().getCurrentPagePackageName(task.service);
        if(Constants.tiktokPackageName.equals(currentPkg)){
            isFindDoing=false;
            return;
        }
        isFindDoing=true;
        task.showLogAndTsPrint("H5页面打开作品链接");
        if(tryTime>=4){
            tryTime=0;
            task.onTaskErr("链接无法跳转,打开tiktok失败");
            finish();
            return;
        }
        tryTime++;
        new Thread(){
            @Override
            public void run() {
//                List<AccessibilityNodeInfo> commentNodes = AccessibilityTool.getInstance().findNodesByText(null,null,task.service, FindIdResouresConfig.openTikTokText1);
//                if(AccessibilityTool.getInstance().isNodeExist(commentNodes)){
//                    openTikTok(task,commentNodes);
//                }else{
//                    List<AccessibilityNodeInfo> commentNodes2 = AccessibilityTool.getInstance().findNodesByText(null,null,task.service, FindIdResouresConfig.openTikTokText2);
//                    if(AccessibilityTool.getInstance().isNodeExist(commentNodes2)){
//                        openTikTok(task,commentNodes2);
//                    }else{
//
//                    }
//                }
                try {
                    //167 1231 913 1366
                    Thread.sleep(8000);
                    int screenXCenter= ScreenUtils.getAppScreenWidth()*4/5;
                    int screenYCenter= (int) (ScreenUtils.getAppScreenHeight()*0.58);
                    String currentPkg = AccessibilityTool.getInstance().getCurrentPagePackageName(task.service);
                    if(Constants.tiktokPackageName.equals(currentPkg)){
                        LogUtils.i("当前已经进入了tiktok页面，无需再点击按钮");
                        finish();
                        isFindDoing=false;
                    }else{
                        int screenYTop= (int) (ScreenUtils.getAppScreenHeight()*0.08);
                        task.showLogAndTsPrint("点击屏幕顶部打开TikTok");
                        AccessibilityTool.getInstance().clickScreen(task.service,screenXCenter,screenYTop);
                        Thread.sleep(4000);
                        currentPkg = AccessibilityTool.getInstance().getCurrentPagePackageName(task.service);
                        if(Constants.tiktokPackageName.equals(currentPkg)){
                            finish();
                            isFindDoing=false;
                            task.changeTaskStatusToStart();
                        }else{
                            task.showLogAndTsPrint("点击屏幕中间打开TikTok");
                            AccessibilityTool.getInstance().clickScreen(task.service,screenXCenter,screenYCenter);
                            Thread.sleep(4000);
                            currentPkg = AccessibilityTool.getInstance().getCurrentPagePackageName(task.service);
                            if(Constants.tiktokPackageName.equals(currentPkg)){
                                finish();
                                isFindDoing=false;
                                task.changeTaskStatusToStart();
                            }else{
                                Thread.sleep(3000);
                                isFindDoing=false;
                                findTopBarAndClick();
                            }
                        }
                    }
                } catch (InterruptedException e) {
                    isFindDoing=false;
                    throw new RuntimeException(e);
                }

            }
        }.start();
    }

    private void openTikTok(BaseTask task, List<AccessibilityNodeInfo> commentNodes) {
        if(task instanceof TikTokTask){
            try {
                TikTokTask tikTokTask= (TikTokTask) task;
                //顶部的按钮
                Thread.sleep(4000);
                clickXy(commentNodes.get(0),task);
                tikTokTask.showLogAndTsPrint("打开tiktok观看作品");
                Thread.sleep(3000);
                String currentPkg = AccessibilityTool.getInstance().getCurrentPagePackageName(tikTokTask.service);
                if(Constants.tiktokPackageName.equals(currentPkg)){
                    finish();
                    isFindDoing=false;
                    tikTokTask.changeTaskStatusToStart();
                }else{
                    redo(task);
                }
            } catch (InterruptedException e) {
                isFindDoing=false;
                throw new RuntimeException(e);
            }
        }else{
            redo(task);
        }
    }

    int redoTime=0;
    private void redo(BaseTask task) {
        if(redoTime>=3){
            task.onTaskErr("链接无法跳转，打开tiktok失败");
            redoTime=0;
            return;
        }
        finish();
        task.delayDo(new BaseTask.SomeThing() {
            @Override
            public void doSomeThing() {
                isFindDoing=false;
                findTopBarAndClick();
            }
        },2000);
    }


    public boolean clickXy(AccessibilityNodeInfo accessibilityNodeInfo,BaseTask task){
        if(accessibilityNodeInfo==null){
            return false;
        }
        Rect rect = new Rect();
        accessibilityNodeInfo.getBoundsInScreen(rect);
        float left = rect.left;
        float right = rect.right;
        float top = rect.top;
        float bottom = rect.bottom;
        int x = (int) ((left + right) / 2);
        int y = (int) ((top + bottom) / 2);
        if(y<0){
            y= (int) (Math.abs(top-bottom)*2);
        }

        LogUtils.i("点击坐标："+x+","+y+"|---"+left+","+top+","+right+","+bottom+"|className="+accessibilityNodeInfo.getClassName());
        boolean isClickSuccess=AccessibilityTool.getInstance().clickScreen(task.service,x,y);
        if(!isClickSuccess){
            LogUtils.w("点击坐标失败了,尝试点击控件");
            return AccessibilityTool.getInstance().click(accessibilityNodeInfo);
        }else {
            LogUtils.i("点击坐标成功了");
            return true;
        }
    }





}
